<template>
  <div class="task-detail-page">
    <div class="breadcrumb-container">
      <el-breadcrumb :separator-icon="ArrowRight" class="breadcrumb-nav">
        <el-breadcrumb-item :to="{ path: '/' }" class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><HomeFilled /></el-icon>
          <span>主页</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item">
          <el-icon class="breadcrumb-icon"><Setting /></el-icon>
          <span>产能管理</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item class="breadcrumb-item active">
          <el-icon class="breadcrumb-icon"><Document /></el-icon>
          <span>任务详情</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="content-card" shadow="never" v-loading="loading">
      <!-- 任务头部信息 -->
      <div class="task-header">
        <div class="task-title">
          <span>{{ taskInfo.processName }}任务 {{ taskInfo.taskCode }}</span>
        </div>
        <div class="task-meta">
          <span>创建人:{{ taskInfo.creator || 'System' }}</span>
          <span>创建时间: {{ formatDateTime(taskInfo.createTime) }}</span>
        </div>
        <div class="task-progress">
          <span>任务进度:</span>
          <el-progress :percentage="Number(taskInfo.taskProgress)" style="width: 300px; margin-left: 12px" />
          <span style="margin-left: 12px">合格/计划:{{ taskInfo.qualifiedQuantity }}/{{ taskInfo.planQuantity }}</span>
        </div>
        <div class="task-actions">
          <el-button v-if="taskInfo.status === 2" type="success" @click="handleStartWork">开工</el-button>
          <el-button v-if="taskInfo.status === 3" type="primary" @click="handleReportWork">报工</el-button>
          <el-button v-if="taskInfo.status === 2 || taskInfo.status === 5" type="danger" @click="handleClose">关闭</el-button>
          <el-button v-if="taskInfo.status === 3" type="success" @click="handleComplete">完成</el-button>
          <el-button v-if="taskInfo.status === 4 || taskInfo.status === 5" type="warning" @click="handleRestart">重启</el-button>
          <el-button @click="handlePrint">打印</el-button>
        </div>
        <div class="task-status">
          <el-tag :type="statusTagType(taskInfo.status)" size="large">{{ statusName(taskInfo.status) }}</el-tag>
        </div>
      </div>

      <!-- 标签页 -->
      <el-tabs v-model="activeTab" class="detail-tabs">
        <!-- 基础信息 -->
        <el-tab-pane label="基础信息" name="basic">
          <div class="tab-content">
            <div class="info-section">
              <div class="info-title">工单信息</div>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="工单编号">{{ workOrderInfo?.workOrderCode }}</el-descriptions-item>
                <el-descriptions-item label="工单名称">{{ workOrderInfo?.workOrderName }}</el-descriptions-item>
                <el-descriptions-item label="产品名称">{{ workOrderInfo?.productName }}</el-descriptions-item>
                <el-descriptions-item label="产品编号">{{ workOrderInfo?.productCode }}</el-descriptions-item>
                <el-descriptions-item label="规格型号">{{ workOrderInfo?.productModel }}</el-descriptions-item>
                <el-descriptions-item label="单位">{{ workOrderInfo?.productUnit }}</el-descriptions-item>
                <el-descriptions-item label="产品类型">{{ productTypeName }}</el-descriptions-item>
                <el-descriptions-item label="BOM">{{ workOrderInfo?.bomCode }}</el-descriptions-item>
              </el-descriptions>
            </div>
            <div class="info-section">
              <div class="info-title">任务信息</div>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="任务编号">{{ taskInfo.taskCode }}</el-descriptions-item>
                <el-descriptions-item label="任务名称">{{ taskInfo.taskName }}</el-descriptions-item>
                <el-descriptions-item label="站点名称">{{ taskInfo.siteName }}</el-descriptions-item>
                <el-descriptions-item label="站点编号">{{ taskInfo.siteCode }}</el-descriptions-item>
                <el-descriptions-item label="工艺路线">{{ taskInfo.processRouteName }}</el-descriptions-item>
                <el-descriptions-item label="工序名称">{{ taskInfo.processName }}</el-descriptions-item>
                <el-descriptions-item label="工序编号">{{ taskInfo.processCode }}</el-descriptions-item>
                <el-descriptions-item label="计划数量">{{ taskInfo.planQuantity }}</el-descriptions-item>
                <el-descriptions-item label="实际生产数量">{{ taskInfo.actualQuantity }}</el-descriptions-item>
                <el-descriptions-item label="计划开工时间">{{ formatDateTime(taskInfo.planStartTime) }}</el-descriptions-item>
                <el-descriptions-item label="计划完工时间">{{ formatDateTime(taskInfo.planEndTime) }}</el-descriptions-item>
                <el-descriptions-item label="实际开工时间">{{ formatDateTime(taskInfo.actualStartTime) }}</el-descriptions-item>
                <el-descriptions-item label="实际完工时间">{{ formatDateTime(taskInfo.actualEndTime) }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </div>
        </el-tab-pane>

        <!-- 派工信息 -->
        <el-tab-pane label="派工信息" name="dispatch">
          <div class="tab-content">
            <div v-if="dispatchInfo?.TaskDispatch" class="info-section">
              <div class="info-title">
                <el-button type="primary" size="small" @click="handleTaskDispatch">任务派工</el-button>
              </div>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="派工人员">{{ dispatchInfo.TaskDispatch.dispatcher }}</el-descriptions-item>
                <el-descriptions-item label="派工时间">{{ formatDateTime(dispatchInfo.TaskDispatch.dispatchTime) }}</el-descriptions-item>
                <el-descriptions-item label="班组名称">{{ dispatchInfo.TaskDispatch.teamName }}</el-descriptions-item>
                <el-descriptions-item label="任务负责人">{{ dispatchInfo.TaskDispatch.responsiblePersonName }}</el-descriptions-item>
                <el-descriptions-item label="其他成员" :span="2">
                  <div v-if="dispatchInfo.TaskDispatch.OtherMembers && dispatchInfo.TaskDispatch.OtherMembers.length > 0">
                    <el-tag
                      v-for="member in dispatchInfo.TaskDispatch.OtherMembers"
                      :key="member.id"
                      style="margin-right: 8px"
                    >
                      {{ member.username }}
                    </el-tag>
                  </div>
                  <span v-else>-</span>
                </el-descriptions-item>
                <el-descriptions-item label="备注" :span="2">{{ dispatchInfo.TaskDispatch.remark || '-' }}</el-descriptions-item>
              </el-descriptions>
            </div>
            <div v-if="dispatchInfo?.QualityDispatch" class="info-section">
              <div class="info-title">
                <el-button type="primary" size="small" @click="handleQualityDispatch">质检派工</el-button>
              </div>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="质检部门">{{ dispatchInfo.QualityDispatch.qualityInspectionDeptName }}</el-descriptions-item>
                <el-descriptions-item label="质检人员">{{ dispatchInfo.QualityDispatch.qualityInspectorName }}</el-descriptions-item>
                <el-descriptions-item label="备注" :span="2">{{ dispatchInfo.QualityDispatch.remark || '-' }}</el-descriptions-item>
              </el-descriptions>
            </div>
            <div v-if="!dispatchInfo?.TaskDispatch && !dispatchInfo?.QualityDispatch" class="empty-state">
              <el-empty description="暂无派工信息" />
            </div>
          </div>
        </el-tab-pane>

        <!-- 物料清单 -->
        <el-tab-pane label="物料清单" name="material">
          <div class="tab-content">
            <div class="material-toolbar">
              <el-button type="primary" @click="handleMaterialOutbound">领料出库</el-button>
              <el-button @click="handleMaterialInbound">退料入库</el-button>
              <el-button @click="handleExport">导出</el-button>
            </div>
            <el-table :data="materialList" border stripe>
              <el-table-column type="index" label="序号" width="70" align="center" />
              <el-table-column prop="materialCode" label="物料编号" min-width="140" />
              <el-table-column prop="materialName" label="物料名称" min-width="160" />
              <el-table-column prop="specification" label="规格型号" min-width="140" />
              <el-table-column prop="unit" label="单位" width="100" align="center" />
              <el-table-column prop="requiredQuantity" label="需求数量" width="120" align="center" />
              <el-table-column prop="materialRatio" label="用料比例" width="120" align="center">
                <template #default="scope">{{ scope.row.materialRatio }}%</template>
              </el-table-column>
              <el-table-column prop="receivedQuantity" label="领用数量" width="120" align="center" />
              <el-table-column prop="returnedQuantity" label="退料数量" width="120" align="center" />
            </el-table>
            <div class="material-summary">
              需求总量:{{ totalRequiredQuantity }} 领用总量:{{ totalReceivedQuantity }} 退料总量:{{ totalReturnedQuantity }}
            </div>
          </div>
        </el-tab-pane>

        <!-- 领料记录 -->
        <el-tab-pane label="领料记录" name="requisition">
          <div class="tab-content">
            <div class="requisition-toolbar">
              <el-button @click="handleExportRequisition">导出</el-button>
            </div>
            <el-table :data="requisitionRecords" border stripe>
              <el-table-column type="index" label="序号" width="70" align="center" />
              <el-table-column prop="requisitionCode" label="领料单编号" min-width="160" />
              <el-table-column prop="requisitionName" label="领料单名称" min-width="160" />
              <el-table-column prop="requisitionDate" label="领料日期" min-width="140">
                <template #default="scope">{{ formatDate(scope.row.requisitionDate) }}</template>
              </el-table-column>
              <el-table-column prop="workOrderName" label="工单名称" min-width="160" />
              <el-table-column prop="workOrderCode" label="工单编号" min-width="160" />
              <el-table-column prop="taskName" label="任务名称" min-width="160" />
              <el-table-column prop="taskCode" label="任务编号" min-width="160" />
              <el-table-column prop="processRouteName" label="工艺路线" min-width="140" />
              <el-table-column prop="processName" label="工序名称" min-width="140" />
              <el-table-column prop="materialInfo" label="物料信息" min-width="200">
                <template #default="scope">
                  {{ scope.row.materialInfo || `物料${scope.row.materialTypeCount}(${scope.row.materialTypeCount}种)` }}
                </template>
              </el-table-column>
            </el-table>
            <div class="requisition-summary">领用总数: {{ totalRequisitionQuantity }}</div>
          </div>
        </el-tab-pane>

        <!-- 退料记录 -->
        <el-tab-pane label="退料记录" name="return">
          <div class="tab-content">
            <el-empty description="暂无退料记录" />
          </div>
        </el-tab-pane>

        <!-- 执行进度 -->
        <el-tab-pane label="执行进度" name="progress">
          <div class="tab-content">
            <el-empty description="执行进度功能开发中" />
          </div>
        </el-tab-pane>
      </el-tabs>

      <div class="footer-actions">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ArrowRight, Document, HomeFilled, Setting } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import https from '@/Http/http'
import { extractPayload, getErrorMessage, getResponseMessage, isRequestSuccess } from '@/utils/responseHelper'

interface TaskInfo {
  id: number
  taskCode: string
  taskName: string
  workOrderId: number
  workOrderCode: string
  workOrderName: string
  siteName: string
  siteCode?: string
  processRouteCode?: string
  processRouteName?: string
  processId: number
  processName: string
  processCode?: string
  planQuantity: number
  actualQuantity: number
  qualifiedQuantity: number
  planStartTime?: string
  planEndTime?: string
  actualStartTime?: string
  actualEndTime?: string
  taskProgress: number
  status: number
  creator?: string
  createTime?: string
}

interface WorkOrderBasicInfo {
  workOrderCode: string
  workOrderName: string
  productName: string
  productCode: string
  productModel?: string
  productUnit?: string
  productTypeId: number
  bomCode?: string
}

interface DispatchDetail {
  dispatcher: string
  dispatchTime: string
  teamName?: string
  responsiblePersonName?: string
  OtherMembers?: Array<{ id: number; username: string }>
  qualityInspectionDeptName?: string
  qualityInspectorName?: string
  remark?: string
}

interface TaskDispatchInfo {
  TaskDispatch?: DispatchDetail
  QualityDispatch?: DispatchDetail
}

interface MaterialItem {
  materialCode: string
  materialName: string
  specification?: string
  unit?: string
  requiredQuantity: number
  materialRatio: number
  receivedQuantity: number
  returnedQuantity: number
}

interface RequisitionRecord {
  requisitionCode: string
  requisitionName: string
  requisitionDate: string
  workOrderCode: string
  workOrderName: string
  taskCode: string
  taskName: string
  processRouteName?: string
  processName: string
  materialInfo?: string
  materialTypeCount: number
  totalQuantity: number
}

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const activeTab = ref('basic')

const taskId = computed(() => Number(route.query.id) || 0)

const taskInfo = reactive<TaskInfo>({
  id: 0,
  taskCode: '',
  taskName: '',
  workOrderId: 0,
  workOrderCode: '',
  workOrderName: '',
  siteName: '',
  siteCode: '',
  processRouteCode: '',
  processRouteName: '',
  processId: 0,
  processName: '',
  processCode: '',
  planQuantity: 0,
  actualQuantity: 0,
  qualifiedQuantity: 0,
  planStartTime: '',
  planEndTime: '',
  actualStartTime: '',
  actualEndTime: '',
  taskProgress: 0,
  status: 0,
  creator: '',
  createTime: ''
})

const workOrderInfo = ref<WorkOrderBasicInfo | null>(null)
const dispatchInfo = ref<TaskDispatchInfo | null>(null)
const materialList = ref<MaterialItem[]>([])
const requisitionRecords = ref<RequisitionRecord[]>([])

const productTypeName = computed(() => {
  // 这里可以根据productTypeId查询产品类型名称
  return '半成品'
})

const totalRequiredQuantity = computed(() => {
  return materialList.value.reduce((sum, item) => sum + Number(item.requiredQuantity), 0)
})

const totalReceivedQuantity = computed(() => {
  return materialList.value.reduce((sum, item) => sum + Number(item.receivedQuantity), 0)
})

const totalReturnedQuantity = computed(() => {
  return materialList.value.reduce((sum, item) => sum + Number(item.returnedQuantity), 0)
})

const totalRequisitionQuantity = computed(() => {
  return requisitionRecords.value.reduce((sum, item) => sum + Number(item.totalQuantity), 0)
})

const loadTaskDetail = async () => {
  if (!taskId.value) {
    ElMessage.error('任务ID不能为空')
    router.back()
    return
  }

  loading.value = true
  try {
    const response = await https.Reads.get('/AShow/TaskDetail', {
      params: { taskId: taskId.value }
    })
    const payload = extractPayload(response)
    if (!isRequestSuccess(payload)) {
      throw new Error(getResponseMessage(payload, '获取任务详情失败'))
    }

    const data = payload?.data ?? payload?.Data
    if (!data) {
      throw new Error('任务详情数据为空')
    }

    // 填充任务信息
    Object.assign(taskInfo, {
      id: data.TaskInfo.id,
      taskCode: data.TaskInfo.taskCode,
      taskName: data.TaskInfo.taskName,
      workOrderId: data.TaskInfo.workOrderId,
      workOrderCode: data.TaskInfo.workOrderCode,
      workOrderName: data.TaskInfo.workOrderName,
      siteName: data.TaskInfo.siteName,
      siteCode: data.TaskInfo.siteCode,
      processRouteCode: data.TaskInfo.processRouteCode,
      processRouteName: data.TaskInfo.processRouteName,
      processId: data.TaskInfo.processId,
      processName: data.TaskInfo.processName,
      processCode: data.TaskInfo.processCode,
      planQuantity: data.TaskInfo.planQuantity,
      actualQuantity: data.TaskInfo.actualQuantity,
      qualifiedQuantity: data.TaskInfo.qualifiedQuantity,
      planStartTime: data.TaskInfo.planStartTime,
      planEndTime: data.TaskInfo.planEndTime,
      actualStartTime: data.TaskInfo.actualStartTime,
      actualEndTime: data.TaskInfo.actualEndTime,
      taskProgress: data.TaskInfo.taskProgress,
      status: data.TaskInfo.status,
      creator: 'System',
      createTime: new Date().toISOString()
    })

    workOrderInfo.value = data.WorkOrderInfo
    dispatchInfo.value = data.DispatchInfo
    materialList.value = data.Materials ?? []
    requisitionRecords.value = data.RequisitionRecords ?? []
  } catch (error) {
    ElMessage.error(getErrorMessage(error, '获取任务详情失败'))
    router.back()
  } finally {
    loading.value = false
  }
}

const handleStartWork = () => {
  ElMessage.info('开工功能开发中')
}

const handleReportWork = () => {
  ElMessage.info('报工功能开发中')
}

const handleClose = () => {
  ElMessage.info('关闭功能开发中')
}

const handleComplete = () => {
  ElMessage.info('完成功能开发中')
}

const handleRestart = () => {
  ElMessage.info('重启功能开发中')
}

const handlePrint = () => {
  ElMessage.info('打印功能开发中')
}

const handleTaskDispatch = () => {
  router.push({ path: '/WorkOrderDispatch', query: { id: taskId.value } })
}

const handleQualityDispatch = () => {
  router.push({ path: '/WorkOrderDispatch', query: { id: taskId.value } })
}

const handleMaterialOutbound = () => {
  ElMessage.info('领料出库功能开发中')
}

const handleMaterialInbound = () => {
  ElMessage.info('退料入库功能开发中')
}

const handleExport = () => {
  ElMessage.info('导出功能开发中')
}

const handleExportRequisition = () => {
  ElMessage.info('导出领料记录功能开发中')
}

const statusTagType = (status: number) => {
  switch (status) {
    case 0:
      return 'info'
    case 1:
      return 'warning'
    case 2:
      return 'success'
    case 3:
      return 'success'
    case 4:
      return 'success'
    case 5:
      return 'danger'
    case 6:
      return 'warning'
    case 7:
      return 'info'
    default:
      return 'info'
  }
}

const statusName = (status: number) => {
  const names: Record<number, string> = {
    0: '未派工',
    1: '已派工',
    2: '已下达',
    3: '进行中',
    4: '已完成',
    5: '已关闭',
    6: '已暂停',
    7: '已撤回'
  }
  return names[status] ?? '未知'
}

const formatDate = (value?: string | Date) => {
  if (!value) return '-'
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return '-'
  const pad = (num: number) => `${num}`.padStart(2, '0')
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
}

const formatDateTime = (value?: string | Date) => {
  if (!value) return '-'
  const date = new Date(value)
  if (Number.isNaN(date.getTime())) return '-'
  const pad = (num: number) => `${num}`.padStart(2, '0')
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}

onMounted(() => {
  loadTaskDetail()
})
</script>

<style scoped>
.task-detail-page {
  padding: 16px;
  min-height: 100%;
  box-sizing: border-box;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.breadcrumb-container {
  margin-bottom: 16px;
  padding: 16px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
}

.breadcrumb-nav :deep(.el-breadcrumb__inner) {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.breadcrumb-item.active :deep(.el-breadcrumb__inner) {
  color: #fff;
  font-weight: 600;
}

.breadcrumb-icon {
  font-size: 16px;
  margin-right: 4px;
}

.content-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
}

.task-header {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 20px;
}

.task-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
}

.task-meta {
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
  display: flex;
  gap: 24px;
}

.task-progress {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.task-actions {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.task-status {
  display: flex;
  justify-content: flex-end;
}

.detail-tabs {
  margin-top: 20px;
}

.tab-content {
  padding: 20px 0;
}

.info-section {
  margin-bottom: 24px;
}

.info-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.material-toolbar,
.requisition-toolbar {
  margin-bottom: 12px;
  display: flex;
  gap: 8px;
}

.material-summary,
.requisition-summary {
  margin-top: 12px;
  text-align: right;
  font-weight: 600;
  color: #303133;
}

.empty-state {
  padding: 40px;
  text-align: center;
}

.footer-actions {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 32px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}
</style>

